// pages/shop/shop/shop.js
var httpUtil = require('../../../utils/httpUtil.js');
var uiUtil = require('../../../utils/uiUtil.js');
var util = require('../../../utils/util.js');
var WXBizDataCrypt = require('../../../utils/cryptoUtil.js');
const appId = 'wx2fda719db8b8c322';
const app = getApp();
var that;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    mchHome:null, //商家信息
    shopCartView:false, //展开购物车

    shopCartLists:[],//购物车列表
    orderGreens:null, //再来一单菜品列表

    chargeStrategy:[], //商家充值规则
    thatIndex: -1, // 充值规则选择下标

    pageThat:"page1", //子页面。page1:点菜；page2:商家;page3:会员;
    categoryId: null, //选择菜单

    scrollChildrens:[],

    icon:{
      pageThat:"home"
    },
    cardDetail: null, //会员卡详情
    sellOutResps:null //售罄菜品列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that=this;
    let mchId = options.mchId;
    if (options.page){
      that.setData({
        pageThat: options.page
      })
    }
    if (options.orderGreens){
      let orderGreens = JSON.parse(options.orderGreens);
      that.setData({
        orderGreens: orderGreens
      })

      that.getShopCart(mchId,function(e){
        if(e.length>0){
          that.getDelCart({ cartId: e[0].id, mchId:mchId},function(e){
            that.anotherOne(orderGreens);
          })
        } else {
          that.anotherOne(orderGreens);
        }
      });
    } else {
      that.getShopCart(mchId);
    }

    that.setData({
      pages: app.globalData.pages,
      authorizeFlag:app.globalData.authorizeFlag
    });

    that.searchMchHome(mchId);
    that.memActivitys(mchId);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (that.data.mchHome) {
      that.ticketDetails();
    }
  },

  /**
   * 转发分享设置
   */
  onShareAppMessage: function (res) {
    return util.handleShareApp('shop', that.data.mchHome)
  },

  /**
   * 充值选择金额
   */
  bindThatChange: function (e) {
    let index = e.currentTarget.dataset.index;
    that.setData({
      thatIndex: index
    })
  },

  /**
   * 提示选择充值金额
   */
  hintCharge:function(e){
    uiUtil.showToast("请选择充值金额");
  },

  /**
   * 跳转到余额明细页面
   */
  balanceDetail(e) {
    if(that.data.cardDetail){
      let id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/pages/ticket/ticket-money/ticket-money?id=' + id
      })
    } else {
      uiUtil.showToast("还未成为会员，无交易明细");
    }
  },

  /**
   * 获取会员卡详细信息
   */
  ticketDetails() {
    let mCardId= that.data.mchHome.memCardId;
    httpUtil.PostRequest("detail", {
      mCardId: mCardId
    }, {
        success(res) {
          that.setData({
            cardDetail: res
          })
        },
        fail(code, res) {
          // uiUtil.showToast(res);
        },
        complete() { }
      })
  },


  /**
   * 获取商户充值规则
   */
  memActivitys(mchId){
    httpUtil.PostRequest("memActivitys", {
      mchId: mchId
    }, {
        success(res) {
          that.setData({
            chargeStrategy: res
          })
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  },

  /**
   * 商家首页查询
   */
  searchMchHome(mchId) {
    httpUtil.PostRequest("searchMchHome", {
      mchId: mchId
    }, {
      success(res) {
        wx.setNavigationBarTitle({
          title: res.mchName
        });
        that.setData({
          mchHome:res,
          categoryId:res.products[0].categoryId
        });
        that.ticketDetails();
        that.scrollChildrenHeight();
      },
      fail(code, res) {
        uiUtil.showToast(res);
      },
      complete() { }
    })
  },

  /**
   * 展开购物车
   */
  shopCartViewChange() {
    if (that.data.shopCartLists.length>0){
      that.setData({
        shopCartView: !that.data.shopCartView
      })
    } 
  },

  /**
   * 购物车查询
   */
  getShopCart(mchId,fun){
    httpUtil.PostRequest("searchCart", {
      mchId: mchId
    }, {
        success(res) {
          
          if (fun){
            fun(res);
          } else {
            if (res.length == 0) {
              that.setData({
                shopCartView: false
              })
            }
            that.setData({
              shopCartLists: res
            })
            uiUtil.hideLoading();
          }
          
        },
        fail(code, res) {
          uiUtil.showToast(res)
        },
        complete() { }
      })
  },

  /**
   * 购物车保存
   */
  getSaveCart(e) {
    let item = e.currentTarget.dataset.item;
    let mchId = that.data.mchHome.mchId;
    let mchName = that.data.mchHome.mchName; 
    let productcount = e.currentTarget.dataset.productcount;
    let type = e.currentTarget.dataset.type;
    productcount = parseInt(productcount) + parseInt(type);
    if (productcount<0){
      return
    }

    httpUtil.PostRequest("saveCart", {
      mchId: mchId,
      mchName: mchName,
      productId: item.productId||item.id,
      productName: item.name || item.productName,
      productImgUrl: item.imageUrl || item.productImgUrl,
      productCount: productcount,
      price: item.price,
      amount: item.price * productcount
    }, {
        success(res) {
          that.getShopCart(mchId);
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  }, 

  /**
   * 购物车删除
   */
  getDelCart(e,fun) {
    let productId ="";
    let cartId = e.cartId|| that.data.shopCartLists[0].id;
    let mchId = e.mchId|| that.data.mchHome.mchId;

    httpUtil.PostRequest("delCart", {
      cartId: cartId,
      productId: productId
    }, {
      success(res) {
        if(fun){
          fun(res);
        } else {
          that.getShopCart(mchId);
        }
      },
      fail(code, res) {
        uiUtil.showToast(res);
      },
      complete() { }
    })
  }, 

  /**
   * 再来一单
   */
  anotherOne(orderGreens){
    httpUtil.PostRequest("anotherOne", {
      mchId: orderGreens.mchId,
      productList: orderGreens.items
    }, {
        success(res) {
          res.sellOutResps=[{
            productId:1,
            productName:2,
            productImgUrl:3,
            price:4
          }]
          console.log(res)
          if (res.sellOutResps.length==0){
            that.getShopCart(orderGreens.mchId);
            that.setData({
              shopCartView: true
            })
          } else {
            that.setData({
              sellOutResps: res.sellOutResps
            })
          }
        },
        fail(code, res) {
          uiUtil.showToast(res);
        }
      })
  },
  sellOutResps(){
    that.setData({
      sellOutResps:null
    })
    that.getShopCart(that.data.orderGreens.mchId);
  },

  /**
   * 收藏商家
   */
  collectChange:function(){
    let mchHome = that.data.mchHome;
    httpUtil.PostRequest("saveCollect", {
      mchId: mchHome.mchId,
      mchName: mchHome.mchName,
      mchAddress: mchHome.mchAddress,
      mchPrice: mchHome.distributionPrice,
      mchType: mchHome.mchType,
      mchLogoUrl: mchHome.mchLogoUrl
    }, {
        success(res) {
          that.setData({
            "mchHome.isCollect":res
          })
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  },

  /**
   * 拨打商家电话
   */
  mchPhone:function(e){
    let phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },

  /**
   * 取消收藏
   */
  delCollectChange:function(){
    let id=that.data.mchHome.isCollect;
    httpUtil.PostRequest("delCollect", {
      id:id
    }, {
        success(res) {
          that.setData({
            "mchHome.isCollect": "0"
          })

          var pages = getCurrentPages();
          var lastPage = pages[pages.length - 2];
          if (lastPage.route == "pages/shop/shop-collect/shop-collect") {
            lastPage.onResultRegisterSuccess();
          }
        },
        fail(code, res) {
          uiUtil.showToast(res);
        }
      })
  },


  /**
   * 点击去结算，获取用户信息
   */
  getuserinfo(e){
    if(e.detail.errMsg=="getUserInfo:fail auth deny"){ //用户拒绝授权获取用户信息
      return
    }
    
    let mchhome=e.currentTarget.dataset.mchhome;
    let shopcartlists=e.currentTarget.dataset.shopcartlists;

    var sessionKey = app.globalData.sessionKey;
    var encryptedData = e.detail.encryptedData;
    var iv =  e.detail.iv;
    var pc = new WXBizDataCrypt(appId, sessionKey)
    var data = pc.decryptData(encryptedData , iv)
    app.globalData.userInfo=data;

    wx.navigateTo({
      url:"/pages/index/order/order-pre/order-pre?mchHome="+mchhome+"&shopCartLists="+shopcartlists
    })
  },
  getuserinfoPageChange(e){
    if(e.detail.errMsg=="getUserInfo:fail auth deny"){ //用户拒绝授权获取用户信息
      return
    }

    var sessionKey = app.globalData.sessionKey;
    var encryptedData = e.detail.encryptedData;
    var iv =  e.detail.iv;
    var pc = new WXBizDataCrypt(appId, sessionKey)
    var data = pc.decryptData(encryptedData , iv)
    app.globalData.userInfo=data;

    that.pageChange(e);
  },


  /**
   * 点击立即充值，获取用户手机号
   */
  getphonenumber (e) {
    if(e.detail.errMsg=="getUserInfo:fail auth deny"){ //用户拒绝授权获取用户手机号
      return
    }

    var sessionKey = app.globalData.sessionKey;
    var encryptedData = e.detail.encryptedData;
    var iv =  e.detail.iv;

    var pc = new WXBizDataCrypt(appId, sessionKey);
    var data = pc.decryptData(encryptedData , iv);
    app.globalData.userPhone=data;

    let mchkey=e.currentTarget.dataset.mchkey;
    let currentPrice=that.data.chargeStrategy[that.data.thatIndex].topUp;
    let activeType=that.data.chargeStrategy[that.data.thatIndex].id;
    that.getUser(mchkey,currentPrice,activeType);
  },


  /**
   * 提交用户信息
   */
  getUser: function (mchkey,currentPrice,activeType){
    let userPhone=app.globalData.userPhone;
    let userInfo=app.globalData.userInfo;
    httpUtil.PostRequest("update_small_user", {
      wechantName: userInfo.nickName,
      phone: userPhone.purePhoneNumber,
      avatarUrl: userInfo.avatarUrl,
      unionId: userInfo.unionId
    }, {
      success(res) {
        app.globalData.authorizeFlag=true;
        that.setData({
          authorizeFlag:true
        })
        wx.navigateTo({
          url:"/pages/pay/pay?mchkey="+mchkey+"&payType=CHARGE&currentPrice="+currentPrice+"&activeType="+activeType
        })
      },
      fail(code, res) {
        uiUtil.showToast(res);
      }
    })
  },


  /**
   * 页面点击操作
   */
  pageChange: function (res) {
    let page = res.currentTarget.dataset.page;
    that.setData({
      pageThat: page
    });

  },
  categoryIdChange: function (res) {
    let categoryId = res.currentTarget.dataset.categoryid;
    that.setData({
      categoryIdIndex: null,
      categoryId: categoryId
    });

  },
  scrollChildrenHeight(){
    let products = that.data.mchHome.products;
    var scrollChildrens=[];
    for (var index = 0; index < products.length;index++){
      let query = wx.createSelectorQuery();
      query.select('#category' + products[index].categoryId).boundingClientRect();
      query.selectViewport().scrollOffset();
      query.exec(function (res) {
        scrollChildrens.push(res[0]);
      })
    }
    that.setData({
      scrollChildrens: scrollChildrens
    })
  },
  scrollHeight:function(e){
    // let y = e.detail.scrollTop;
    // let scrollChildrens = that.data.scrollChildrens;
    
    // console.log(y, scrollChildrens);
    // for (let index = 0; index < scrollChildrens.length;index++){
    //   let top = scrollChildrens[index].top;
    //   let nextTop = scrollChildrens[index+1].top;
    //   console.log(top, nextTop);
    //   if (y >= top && (y < nextTop || nextTop==0)){
    //     console.log(index)
    //     that.setData({
    //       categoryId:null,
    //       categoryIdIndex: index
    //     })
    //     return ;
    //   }
    // }
  }
})